package com.itheima.stock;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.itheima.stock.pojo.User;

import org.junit.jupiter.api.Test;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class testEasyExcel {

    public List<User> init() {
        //组装数据
        ArrayList<User> users = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            User user = new User();
            user.setAddress("上海" + i);
            user.setUserName("张三" + i);
            user.setBirthday(new Date());
            user.setAge(10 + i);
            users.add(user);
        }
        return users;
    }

    //导出excel
    @Test
    public void Test1() {
        List<User> users = init();
        EasyExcel.write("D:\\user.xls", User.class)
                .sheet("测试").doWrite(users);
    }

    //excel导入
    @Test
    public void ExcelImport() {
        ArrayList<User> users = new ArrayList<>();
        EasyExcel.read("D:\\user.xls", User.class, new AnalysisEventListener<User>() {
            /**
             * 逐行读取，读取一行，则回调invoke方法
             * @param user
             * @param analysisContext
             */
            @Override
            public void invoke(User user, AnalysisContext analysisContext) {
                //模拟保存在mysql中
                System.out.println(user);
                users.add(user);
            }

            //读取完毕后调用该方法
            @Override
            public void doAfterAllAnalysed(AnalysisContext analysisContext) {
                System.out.println("读取完成");
            }
            //这里sheet中不能有参数，否则获取不到内容
        }).sheet().doRead();
        System.out.println(users);
    }

    @Test
    public void readExcel() {
        ArrayList<User> users = new ArrayList<>();
        //读取数据
        EasyExcel.read("D:\\user.xls", User.class, new AnalysisEventListener<User>() {
            @Override
            public void invoke(User o, AnalysisContext analysisContext) {
                System.out.println(o);
                users.add(o);
            }

            @Override
            public void doAfterAllAnalysed(AnalysisContext analysisContext) {
                System.out.println("完成。。。。");
            }
        }).sheet().doRead();
        System.out.println(users);
    }
}
